import json

from django.http import JsonResponse
from meiduo_move_server.utils import request_utils
from meiduo_move_server.utils import img_utils
from meiduo_move_server.utils.mysql_utils import MySQLUtils
from meiduo_move_server import project_constants as p_const
from meiduo_move_server.utils import data_type_change_utils
from user.utils import jwt_utils


# Create your views here.
def addGoods(req):
    """
    向数据库中添加商品信息

    @param - req: 请求信息对象

    @return: 响应对象
    """
    body = request_utils.getPostDataToDict(req.body)
    # print(body)
    goodsPrice = body.get('goodsPrice')  # 获取商品数据中的价格
    goodsName = body.get('goodsName')  # 获取商品数据中的商品名
    goodsFreight = body.get('goodsFreight')  # 获取商品数据中的商品运费
    goodsCount = body.get('goodsCount')  # 获取商品数据中的商品库存
    goodsCategory = body.get('goodsCategory')  # 获取商品数据中的商品类别
    goodsParams = body.get('goodsParams')  # 获取商品数据中的商品参数类别及其参数值
    fileList = body.get('fileList')  # 获取商品数据中的图片
    goods_picture_paths = img_utils.base64ToImg(files=fileList, goodsCategory=goodsCategory, goodsName=goodsName)  # 保存图片
    sql= """
    SELECT f_insert_goods_info(%s, %s, %s, %s, %s);
    """
    res = MySQLUtils.updateAndSelect(sql, (goodsName, goodsPrice, goodsFreight, goodsCount, goodsCategory))
    if res.get('row_count') < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '商品信息添加失败'
        })
    newGoodsInfoId = res.get('data')[0][0]  # 得到新商品在商品信息表中的id
    # 向商品参数信息表中添加信息
    for goodsParam in goodsParams:
        paramCategory = goodsParam.get('paramCategory')
        param = goodsParam.get('param')
        sql = """
        CALL p_insert_goods_param_info(%s, %s, %s);
        """
        res = MySQLUtils.update(sql, (paramCategory, param, newGoodsInfoId))
        if res < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '商品信息添加失败'
            })
    # 向商品图片信息表添加图片路径信息
    for goodsPicturePath in goods_picture_paths:
        sql = """
        CALL p_insert_goods_picture_info(%s, %s);
        """
        res = MySQLUtils.update(sql, (goodsPicturePath, newGoodsInfoId))
        if res < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '商品信息添加失败'
            })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '商品信息添加成功'
    })


def getGoodsList(req):
    """
    获取还有库存的商品数据，用于商品列表展示，商品第一张图片和商品名、商品id、商品价格、商品销售量
    """
    category = req.GET.get('category')
    searchContent = req.GET.get('searchContent')
    if category is not None:
        sql = """
        SELECT id, goods_name, goods_price, goods_sale_number, goods_freight, goods_comment_number
        FROM goods_info
        WHERE goods_count > 0 AND goods_category = %s
        ORDER BY id DESC;
        """
        goods_list_data = MySQLUtils.select(sql, (category,))
    elif searchContent is not None:
        sql = """
        SELECT id, goods_name, goods_price, goods_sale_number, goods_freight, goods_comment_number
        FROM goods_info
        WHERE goods_count > 0 AND (goods_name LIKE %s OR goods_category LIKE %s)
        ORDER BY id DESC;
        """
        searchContentWord = list(searchContent)
        searchContent = '%'
        for i in searchContentWord:
            searchContent += i + '%'
        # print(searchContent)
        goods_list_data = MySQLUtils.select(sql, (searchContent, searchContent))
    else:
        sql="""
        SELECT id, goods_name, goods_price, goods_sale_number, goods_freight, goods_comment_number
        FROM goods_info
        WHERE goods_count > 0
        ORDER BY id DESC;
        """
        goods_list_data = MySQLUtils.select(sql)
    row_count = goods_list_data.get('row_count')
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '获取商品列表信息失败',
        })
    goods_list = goods_list_data.get('data')
    goods_list = data_type_change_utils.tuple2dict(['id', 'goodsName', 'goodsPrice', 'goodsSaleNumber', 'goodsFreight', 'goodsCommentNumber'], goods_list)
    index = 0
    while index < row_count:
        sql = """
        SELECT goods_picture_path
        FROM goods_picture_info
        WHERE goods_info_id = %s
        LIMIT 1;
        """
        goodsPicturePath = MySQLUtils.select(sql, (goods_list[index]['id'],))
        if goodsPicturePath.get('row_count') < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '获取商品列表信息失败',
            })
        goods_list[index]['goodsPicturePath'] = goodsPicturePath.get('data')[0][0]
        index += 1
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取商品列表信息成功',
        'goodsList': goods_list
    })


def getGoodsDetailInfo(req):
    """
    获取商品的详细信息，商品图片、商品名、商品价格、商品销售量、商品运费、商品参数、商品评论数
    """
    goodsId = req.GET.get('goodsId')
    # print(goodsId)
    sql = """
    SELECT id, goods_name, goods_price, goods_sale_number, goods_freight, goods_comment_number
    FROM goods_info WHERE id = %s;
    """
    res_data = MySQLUtils.select(sql, (goodsId,))
    if res_data.get('row_count') < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '暂无该商品详细信息'
        })
    goods_data = res_data.get('data')
    goods_data = data_type_change_utils.tuple2dict(
        ['goodsId', 'goodsName', 'goodsPrice', 'goodsSaleNumber', 'goodsFreight', 'goodsCommentNumber'],
        goods_data
    )[0]
    sql = """
    SELECT goods_picture_path FROM goods_picture_info WHERE goods_info_id = %s;
    """
    res_data = MySQLUtils.select(sql, (goodsId,))
    # if res_data.get('row_count') < 1:
    #     return JsonResponse({
    #         'mark': p_const.MARK_ERROR,
    #         'message': '暂无该商品详细信息'
    #     })
    i = 0
    goodsPicturePath = list()
    while i < res_data.get('row_count'):
        goodsPicturePath.append(res_data.get('data')[i][0])
        i += 1
    goods_data['goodsPicturePath'] = goodsPicturePath
    sql = """
    SELECT param_category, param FROM goods_param_info WHERE goods_info_id=%s;
    """
    res_data = MySQLUtils.select(sql, (goodsId,))
    # if res_data.get('row_count') < 1:
    #     return JsonResponse({
    #         'mark': p_const.MARK_ERROR,
    #         'message': '暂无该商品详细信息'
    #     })
    goods_data['goodsParams'] = res_data.get('data')
    # print(goods_data)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '商品详细信息获取成功',
        'data': goods_data
    })

